<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="JVM,">










<meta name="description" content="前面介绍了方法的调用过程，简单的方法可以在我们自己写的 JVM 中运行起来了，但是方法的执行过程并不完整，因为方法可能会抛出异常，我们暂时还无法处理异常。本节依然通过示例来讲解异常的处理机制。进一步完善我们的 JVM。核心是 athrow 指令的实现">
<meta name="keywords" content="JVM">
<meta property="og:type" content="article">
<meta property="og:title" content="手写JVM系列(18)异常处理机制">
<meta property="og:url" content="https://zachaxy.github.io/2018/01/20/手写JVM系列-18-异常处理机制/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="前面介绍了方法的调用过程，简单的方法可以在我们自己写的 JVM 中运行起来了，但是方法的执行过程并不完整，因为方法可能会抛出异常，我们暂时还无法处理异常。本节依然通过示例来讲解异常的处理机制。进一步完善我们的 JVM。核心是 athrow 指令的实现">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-01T11:13:24.304Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="手写JVM系列(18)异常处理机制">
<meta name="twitter:description" content="前面介绍了方法的调用过程，简单的方法可以在我们自己写的 JVM 中运行起来了，但是方法的执行过程并不完整，因为方法可能会抛出异常，我们暂时还无法处理异常。本节依然通过示例来讲解异常的处理机制。进一步完善我们的 JVM。核心是 athrow 指令的实现">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/2018/01/20/手写JVM系列-18-异常处理机制/">





  <title>手写JVM系列(18)异常处理机制 | zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">


  <div id="posts" class="posts-expand">








  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2018/01/20/手写JVM系列-18-异常处理机制/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">手写JVM系列(18)异常处理机制</h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-20T16:58:41+08:00">
                2018-01-20
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  2,620
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">





        <p>前面介绍了方法的调用过程，简单的方法可以在我们自己写的 JVM 中运行起来了，但是方法的执行过程并不完整，因为方法可能会抛出异常，我们暂时还无法处理异常。本节依然通过示例来讲解异常的处理机制。进一步完善我们的 JVM。核心是 <a href="https://github.com/zachaxy/JVM/blob/master/Java/src/instructions/references/ATHROW.java" target="_blank" rel="noopener">athrow 指令的实现</a></p>
<a id="more"></a>

<h1 id="本节异常处理机制所用的示例"><a href="#本节异常处理机制所用的示例" class="headerlink" title="本节异常处理机制所用的示例"></a>本节异常处理机制所用的示例</h1><p>本节所讲解的异常处理机制是基于以下面的例子做说明的，有两个方法，(1)func 方法直接抛出了一个异常；(2)test 方法调用了 func 方法，同时试图用 try-catch 来捕获异常，但是其所捕获的异常并非 func 抛出的异常，也就是说 test 方法处理不了，最终交由 JVM 来处理，而 JVM 默认的处理方式则是打印虚拟机堆栈信息。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i = <span class="number">100</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        func();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (NumberFormatException e) &#123;</span><br><span class="line">        i = <span class="number">200</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">func</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> IndexOutOfBoundsException();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>test 方法的字节码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"> 0 bipush 100</span><br><span class="line"> 2 istore_0</span><br><span class="line"> 3 invokestatic #60 &lt;test/TestException12.func&gt;</span><br><span class="line"> 6 goto 14 (+8)</span><br><span class="line"> 9 astore_1</span><br><span class="line">10 sipush 200</span><br><span class="line">13 istore_0</span><br><span class="line">14 return</span><br></pre></td></tr></table></figure>

<h1 id="直观的感受-athrow-命令"><a href="#直观的感受-athrow-命令" class="headerlink" title="直观的感受 athrow 命令"></a>直观的感受 athrow 命令</h1><p>由上面的 func 方法，其方法体直接通过 throw 关键字抛出了一个异常，那么查看 func 方法对应的字节码:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">0 new #62 &lt;java/lang/IndexOutOfBoundsException&gt;</span><br><span class="line">3 dup</span><br><span class="line">4 invokespecial #63 &lt;java/lang/IndexOutOfBoundsException.&lt;init&gt;&gt;</span><br><span class="line">7 athrow</span><br></pre></td></tr></table></figure>

<p>前面的三个指令是在创建 IndexOutOfBoundsException 异常的一个实例，并执行其 init 方法。<br>接下来就是一个 athrow 命令，将上面创建的异常抛出。这就是 athrow 指令出现的场景。现在只是只管的感受一下 athrow 指令，暂时先不去实现它。</p>
<h1 id="异常处理表"><a href="#异常处理表" class="headerlink" title="异常处理表"></a>异常处理表</h1><p>func 方法内部抛出了异常，那么接下来需要另一个方法 test 来调用 func 方法。在 test 方法中，我们 catch 了一个异常 NumberFormatException，但是该异常的类型并不是 func 方法抛出的异常，因此是不会执行对应的 catch 块的。我们通过定义一个变量 i 来标示，如果执行了 catch 块，那么该变量 i 会变为 200，否则还是初值 100；</p>
<p>如果在方法中使用了 try-catch 语句，那么在该方法的 code 属性中就会有一个异常处理表。这里之所以叫表，是因为我们可能会 catch 多个异常，每 catch 一个异常，就会产生一条表项。<br>在上面的 test 方法中就有异常表，因为我们这里只有一个 catch，所以异常表只有一条表项</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    start:3</span><br><span class="line">    end:6</span><br><span class="line">    hadlerPC:9</span><br><span class="line">    catchType: #5 (java/lang/NumberFormatException)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>JVM 中定义的异常处理表项有四个字段：均为整数</p>
<ul>
<li>startPc</li>
<li>endPc</li>
<li>handlerPc</li>
<li>catchType</li>
</ul>
<p>其含义如下：<br>[startPc,endPc) 一个区间:锁定一个指令区间,该区间可能抛出某种异常。test 的异常表表示在字节码 3 到字节码 6(不包含 6)之间，可能会抛出异常，而指令 3 正是调用了抛出异常的 func 方法。<br>handlerPc:负责处理异常的 catch 块的其实位置，一旦发现某个 catch 可以处理该异常，那么就将 nextPc 改为 handlerPc。<br>catchType:指向运行时常量池的一个索引,通过该索引可以得到一个异常的类 xxxException 的对象，也就是我们在代码中显式 catch 的异常的类型。</p>
<h1 id="解析异常处理表"><a href="#解析异常处理表" class="headerlink" title="解析异常处理表"></a>解析异常处理表</h1><p>和之前的常量池类似，异常处理表也是保存 class 文件中，我们在读取 class 文件的时候，一样要对其进行转换。<br>首先看一下其在 ClassFile 中的表现形式:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">ExceptionTableEntry</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> startPc;        <span class="comment">//可能排除异常的代码块的起始字节码（包括）</span></span><br><span class="line">    <span class="keyword">int</span> endPc;          <span class="comment">//可能排除异常的代码块的终止字节码（不包括）</span></span><br><span class="line">    <span class="keyword">int</span> handlerPc;      <span class="comment">//负责处理异常的 catch 块的其实位置</span></span><br><span class="line">    <span class="keyword">int</span> catchType;      <span class="comment">//指向运行时常量池的一个索引，解析后可以得到一个异常类</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其在 Zclass 中的表现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ExceptionHandler</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> startPc;</span><br><span class="line">    <span class="keyword">int</span> endPc;</span><br><span class="line">    <span class="keyword">int</span> handlerPc;</span><br><span class="line">    ClassRef catchType;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对比发现，具体的转换是将 catchType 运行时常量池的常量直接转换为对应的异常类的引用，其转换过程是在 ClassFile-&gt;Zclass 的转换过程中，具体对应到方法的转换过程。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">Zclass</span><span class="params">(ClassFile classFile)</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    runtimeConstantPool = <span class="keyword">new</span> RuntimeConstantPool(<span class="keyword">this</span>, classFile.getConstantPool());</span><br><span class="line">    fileds = Zfield.makeFields(<span class="keyword">this</span>, classFile.getFields());</span><br><span class="line">    methods = Zmethod.makeMethods(<span class="keyword">this</span>, classFile.getMethods());</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="athorw-命令的实现-异常处理流程"><a href="#athorw-命令的实现-异常处理流程" class="headerlink" title="athorw 命令的实现(异常处理流程)"></a>athorw 命令的实现(异常处理流程)</h1><p>再次贴出 test 方法的代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> i = <span class="number">100</span>;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        func();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (NumberFormatException e) &#123;</span><br><span class="line">        i = <span class="number">200</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>test 对应的栈帧为 frame1，当其内部执行 func 方法时，会为其创建栈帧 frame2，在 frame2 中执行 func 方法，在 func 方法中，首先创建了一个异常——IndexOutOfBoundsException 的对象，该对象放在 frame2 的操作数栈顶。然后遇到了 athrow 命令，该指令将 frame2 操作数栈顶的异常对象 ex pop 出来，然后从当前 frame 开始遍历虚拟机栈。我们知道当前 JVM 的栈为 frame1 -&gt; frame2。那么先从 frame2 开始，查找当前方法的异常处理表，当然我们一般在写代码的时候不会在手动写了 throw 异常之后，立刻在当前方法就去 catch 它，我们一般的做法都是在 func 方法的声明处显示的 throws 对应的异常，等待调用 func 的上层方法来出来，但是语法也是允许自己来 catch 的，所以先从 frame2 查找，查找不到，那么将 frame2 从虚拟机栈弹出，然后再从当前栈顶的 frame1 中查找是否可以找到异常处理项，就这样一直遍历下去。</p>
<p>这样的遍历会产生两个结果：</p>
<ol>
<li>在某个 frame 中找到了可以处理该异常的项，那么首先到该 frame 的操作数栈清空，然后把异常对象压入当前操作数栈，接着执行该 frame 对应的 catch 块语句。</li>
<li>遍历了整个虚拟机栈都没有找到可以处理的异常项，因此交由 JVM 来处理，而 JVM 的处理方式就是打印虚拟机栈信息(从产生异常的方法 func 对应的 frame，依次到 main 方法对应的 frame)</li>
</ol>
<p>athrow 指令的处理流程：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Zobject ex = frame.getOperandStack().popRef();</span><br><span class="line"></span><br><span class="line"><span class="comment">//获取当前 thread,是想从 thread 中获取所有的 frame(一个 frame 就是一个方法调用过程的抽象)</span></span><br><span class="line">Zthread thread = frame.getThread();</span><br><span class="line"><span class="keyword">if</span> (!findAndGotoExceptionHandler(thread, ex)) &#123;</span><br><span class="line">    <span class="comment">//所有的方法调用栈均不能处理该异常了,那么交由 JVM 来处理;</span></span><br><span class="line">    handleUncaughtException(thread, ex);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面多次提到了在当前 frame 寻找对应的异常处理项，如何寻找，这就用到了 findAndGotoExceptionHandler 方法，具体流程如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">//从当前帧开始,遍历 Java 虚拟机栈,查找方法的异常处理表</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">findAndGotoExceptionHandler</span><span class="params">(Zthread thread, Zobject ex)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">        Zframe frame = thread.getCurrentFrame();</span><br><span class="line">        <span class="comment">//正常情况下,获取一条指令后,bytereader 中的 pc 是要+1,指向下一条指令的地址</span></span><br><span class="line">        <span class="comment">// 但是 athrow 指令比较特殊,因为现在已经抛出异常了,不能继续向下执行了,所以要回退;</span></span><br><span class="line">        <span class="keyword">int</span> pc = frame.getNextPC() - <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//此时 pc 指向的是 throw 异常的那一行;因为接下来就要在当前方法的异常处理表中寻找可以处理当前 pc 指向的指令所抛出的异常了</span></span><br><span class="line">        <span class="keyword">int</span> handlerPC = frame.getMethod().findExceptionHandler(ex.getClazz(), pc);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//当前方法能处理自己抛出的异常</span></span><br><span class="line">        <span class="keyword">if</span> (handlerPC &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            OperandStack operandStack = frame.getOperandStack();</span><br><span class="line">            operandStack.clear();<span class="comment">//清空操作数栈</span></span><br><span class="line">            operandStack.pushRef(ex);<span class="comment">//将抛出的异常放进去</span></span><br><span class="line">            frame.setNextPC(handlerPC);<span class="comment">//指令跳转到对应的 catch 块中</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//能走到这一步,说明当前方法不能处理当前方法抛出的异常,需要回到调用该方法的帧 frame</span></span><br><span class="line">        thread.popFrame();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//整个调用栈都无法处理异常，交由 JVM 来处理吧；JVM 处理的方法就是下面的 handleUncaughtException</span></span><br><span class="line">        <span class="keyword">if</span> (thread.isStackEmpty()) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>超找异常处理项，最终是在 Method 的 ExceptionTable 对象中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//返回能解决当前 Exception 的 handler=&gt;多个 catch 块,决定用哪个</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> ExceptionHandler <span class="title">findExceptionHandler</span><span class="params">(Zclass exClazz, <span class="keyword">int</span> pc)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; exceptionTable.length; i++) &#123;</span><br><span class="line">        ExceptionHandler handler = exceptionTable[i];</span><br><span class="line">        <span class="keyword">if</span> (pc &gt;= handler.startPc &amp;&amp; pc &lt; handler.endPc) &#123;</span><br><span class="line">            <span class="comment">// catch all</span></span><br><span class="line">            <span class="keyword">if</span> (handler.catchType == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">return</span> handler;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 如果 catch 的异常是实际抛出的异常的父类，也可以捕获</span></span><br><span class="line">            Zclass catchClazz = handler.catchType.resolvedClass();</span><br><span class="line">            <span class="keyword">if</span> (catchClazz == exClazz || catchClazz.isSuperClassOf(exClazz)) &#123;</span><br><span class="line">                <span class="keyword">return</span> handler;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面能找到对应的异常处理项，那么整个程序还可以正常运行，但如果没有找到的话，就要交给 JVM 来处理的，此时也意味着当前的虚拟机栈已经被清空了，解释器也停止执行了，JVM 将整个调用链打印出来，程序结束。</p>
<h1 id="Java-虚拟机栈信息"><a href="#Java-虚拟机栈信息" class="headerlink" title="Java 虚拟机栈信息"></a>Java 虚拟机栈信息</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NStackTraceElement</span> </span>&#123;</span><br><span class="line">    String fileName;<span class="comment">//类所在的 java 文件</span></span><br><span class="line">    String className;<span class="comment">//声明方法的类名</span></span><br><span class="line">    String methodName;<span class="comment">//调用方法名</span></span><br><span class="line">    <span class="keyword">int</span> lineNumber;<span class="comment">//出现 exception 的行号</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>NStackTraceElement 代表每个 frame 中调用抛出异常方法的具体消息。</p>
<p>上面实现了 ATHROW 命令，但是目前程序还是无法运行，因为异常的父类 Exception 的构造方法中会调用一个 native 的方法——fillInStackTrace，因此还要在 native 方法中注册 fillInStackTrace 方法，同时在该方法中进行虚拟机调用栈的收集工作。<br>具体的代码请参考<a href="https://github.com/zachaxy/JVM/blob/master/Java/src/znative/java/lang/Nthrowable" target="_blank" rel="noopener">Nthrowable.java</a>，注释已经写的很清楚，相信不会有太大的阅读困难。</p>
<h1 id="异常的测试用例"><a href="#异常的测试用例" class="headerlink" title="异常的测试用例"></a>异常的测试用例</h1><p>同样，这里提供了一个单独的<a href="https://github.com/zachaxy/JVM/blob/master/Java/src/test/TestException12.java" target="_blank" rel="noopener">测试用例</a>来测试异常，我们的 test 方法并没有不会 func 方法抛出的异常，这一点从最终打印 test 的本地变量表就可以发现，i 的值为 100，没有走到 catch 语句中。同时程序也打印出了虚拟机堆栈信息，具体打印信息如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">the same as testInterpreter06!</span><br><span class="line">java -cp /Users/zachaxy/TestClassFiles  TestException12</span><br><span class="line">current instruction: 0: BIPUSH</span><br><span class="line">current instruction: 2: ISTORE_0</span><br><span class="line">current instruction: 3: INVOKE_STATIC</span><br><span class="line">current instruction: 3: INVOKE_STATIC</span><br><span class="line">test.TestException12.f1(TestException12.java:82)</span><br><span class="line">test.TestException12.test(TestException12.java:75)</span><br><span class="line">100</span><br></pre></td></tr></table></figure>

    </div>









      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zachaxy
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zachaxy.github.io/2018/01/20/手写JVM系列-18-异常处理机制/" title="手写JVM系列(18)异常处理机制">https://zachaxy.github.io/2018/01/20/手写JVM系列-18-异常处理机制/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>


    <footer class="post-footer">

        <div class="post-tags">

            <a href="/tags/JVM/" rel="tag"># JVM</a>

        </div>







        <div class="post-nav">
          <div class="post-nav-next post-nav-item">

              <a href="/2018/01/18/手写JVM系列-17-本地方法的调用过程/" rel="next" title="手写JVM系列(17)本地方法的调用过程">
                <i class="fa fa-chevron-left"></i> 手写JVM系列(17)本地方法的调用过程
              </a>

          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">

              <a href="/2018/01/23/TestMusic/" rel="prev" title="TestMusic">
                TestMusic <i class="fa fa-chevron-right"></i>
              </a>

          </div>
        </div>




    </footer>
  </div>



  </article>



    <div class="post-spread">

    </div>
  </div>


          </div>









        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">




        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>


      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>


      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">






              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#本节异常处理机制所用的示例"><span class="nav-number">1.</span> <span class="nav-text">本节异常处理机制所用的示例</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#直观的感受-athrow-命令"><span class="nav-number">2.</span> <span class="nav-text">直观的感受 athrow 命令</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#异常处理表"><span class="nav-number">3.</span> <span class="nav-text">异常处理表</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#解析异常处理表"><span class="nav-number">4.</span> <span class="nav-text">解析异常处理表</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#athorw-命令的实现-异常处理流程"><span class="nav-number">5.</span> <span class="nav-text">athorw 命令的实现(异常处理流程)</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Java-虚拟机栈信息"><span class="nav-number">6.</span> <span class="nav-text">Java 虚拟机栈信息</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#异常的测试用例"><span class="nav-number">7.</span> <span class="nav-text">异常的测试用例</span></a></li></ol></div>


          </div>
        </section>
      <!--/noindex-->




    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>







  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>






  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
